package cn.hd.authorService.vo;

import cn.hd.commonService.entity.SysUser;
import cn.hd.commonService.vo.function.FunctionAuthorityVo;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser user;

    private List<FunctionAuthorityVo> permissions;

    public LoginUser(SysUser user, List<FunctionAuthorityVo> permissions) {
        this.user = user;
        this.permissions = permissions;
    }
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities  = new ArrayList<>();
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        for (FunctionAuthorityVo functionAuthorityVo : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(StrUtil.isBlank(functionAuthorityVo.getPerms())?"-":functionAuthorityVo.getPerms());
            authorities.add(authority);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
